#!/usr/bin/python3
# _*_ coding:utf-8 _*_
# __author__ = '__Csm__'
# 一般对数据的操作和统计相关的功能写到模型类里，一些逻辑处理放到视图里面
# 1. 需要返回查询集的逻辑写在QuerySetModel中
# 2. 模型类中数据库处理的逻辑写在Models中
# 3. 业务相关逻辑的处理写在Views中

from __future__ import unicode_literals
import uuid

from six import python_2_unicode_compatible
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models


@python_2_unicode_compatible
class MessageQuerySet(models.query.QuerySet):

    def get_conversation(self, sender, recipient):
        """用户间私信会话"""
        qs_one =self.filter(sender=sender, recipient=recipient)#  A给B发送消息
        qs_two =self.filter(sender=recipient, recipient=sender)#  B给A发送消息
        return qs_one.union(qs_two).order_by('created_at')  #  取并集后按照时间排序

    def get_most_recent_conversation(self, recipient):
        """最近一次私信的用户"""
        try:
            qs_send = self.filter(sender=recipient)#当前登录用户发送的消息
            qs_received = self.filter(recipient=recipient)#当前登录用户接收的消息
            qs = qs_send.union(qs_received).latest('created_at')#最后一条消息
            if qs.sender == recipient:
                # 如果登录用户有发送消息，返回消息的接收者
                return qs.recipient
            # 否则返回消息的发送者
            return qs.sender
        except self.model.DoesNotExist:
            # 如果模型实例不存在，则返回当前用户
            return get_user_model().objects.get(username=recipient.username)



@python_2_unicode_compatible
class Message(models.Model):
    """用户私信"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sent_messages', blank=True, null=True, on_delete=models.SET_NULL, verbose_name="发送者")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='received_me', blank=True, null=True, on_delete=models.SET_NULL, verbose_name="接收者")
    message = models.TextField(blank=True, null=True, verbose_name="内容")
    unread = models.BooleanField(default=False, db_index=True, verbose_name="是否已读")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") #消息只有创建时间，不能修改，所以没有update_at
    objects = MessageQuerySet.as_manager()

    class Meta:
        verbose_name = "私信"
        verbose_name_plural = verbose_name
        ordering = ['-created_at', ]

    def __str__(self):
        return self.message

    def mark_as_read(self):
        if self.unread:
            self.unread = False
            self.save()

